import axios from "axios";
import store from '@/store/index'
import { Message } from "element-ui";
import router from "@/router";

const service = axios.create({
  baseURL:process.env.VUE_APP_BASE_API,
  timeout: 10000,
})

service.interceptors.request.use(config => {
  if (store.getters.token) {
    config.headers['Authorization'] = 'Bearer ' + store.getters.token
  }
  return config
},err => {
  Message({ type:"error",message:err.message})
  return Promise.reject(err)
})

// 响应拦截器
service.interceptors.response.use((response) =>{
  const {data,message,success} = response.data
  if(success) {
    return data
  }else {
    Message({ type:"error",message:message})
    return Promise.reject(new Error(message))
  }
},async error => {
  if(error.response.status == 401) {
    // 说明token失效 退出登录 返回登录页面
    await store.dispatch('user/logout')
    router.push({path:'/login'})
    Message({ type:"error",message:'身份认证已过期!'})
    return Promise.reject(error)
  }
  Message({ type:"error",message:error.message})
  return Promise.reject(error)
})

export default service